{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "“模型基本训练_保存_下载.ipynb”的副本",
      "version": "0.3.2",
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true,
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/yejianfeng2014/AI/blob/master/%E2%80%9C%E6%A8%A1%E5%9E%8B%E5%9F%BA%E6%9C%AC%E8%AE%AD%E7%BB%83_%E4%BF%9D%E5%AD%98_%E4%B8%8B%E8%BD%BD_ipynb%E2%80%9D%E7%9A%84%E5%89%AF%E6%9C%AC.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "metadata": {
        "id": "he9Ee2-XtL1Z",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "挂载云硬盘，如果验证数据请填写验证信息 挂载硬盘，**只需要挂载一次**"
      ]
    },
    {
      "metadata": {
        "id": "hK5MYRMbf12-",
        "colab_type": "code",
        "outputId": "50d0fe0a-5de9-4e5c-e379-27fe09ce3e44",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 379
        }
      },
      "cell_type": "code",
      "source": [
        "!apt-get install -y -qq software-properties-common python-software-properties module-init-tools\n",
        "!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null\n",
        "!apt-get update -qq 2>&1 > /dev/null\n",
        "!apt-get -y install -qq google-drive-ocamlfuse fuse\n",
        "from google.colab import auth\n",
        "auth.authenticate_user()\n",
        "from oauth2client.client import GoogleCredentials\n",
        "creds = GoogleCredentials.get_application_default()\n",
        "import getpass\n",
        "!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL\n",
        "vcode = getpass.getpass()\n",
        "!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}"
      ],
      "execution_count": 0,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "E: Package 'python-software-properties' has no installation candidate\n",
            "Selecting previously unselected package libfuse2:amd64.\n",
            "(Reading database ... 22280 files and directories currently installed.)\n",
            "Preparing to unpack .../libfuse2_2.9.7-1ubuntu1_amd64.deb ...\n",
            "Unpacking libfuse2:amd64 (2.9.7-1ubuntu1) ...\n",
            "Selecting previously unselected package fuse.\n",
            "Preparing to unpack .../fuse_2.9.7-1ubuntu1_amd64.deb ...\n",
            "Unpacking fuse (2.9.7-1ubuntu1) ...\n",
            "Selecting previously unselected package google-drive-ocamlfuse.\n",
            "Preparing to unpack .../google-drive-ocamlfuse_0.7.0-0ubuntu1~ubuntu18.04.1_amd64.deb ...\n",
            "Unpacking google-drive-ocamlfuse (0.7.0-0ubuntu1~ubuntu18.04.1) ...\n",
            "Setting up libfuse2:amd64 (2.9.7-1ubuntu1) ...\n",
            "Processing triggers for libc-bin (2.27-3ubuntu1) ...\n",
            "Setting up fuse (2.9.7-1ubuntu1) ...\n",
            "Setting up google-drive-ocamlfuse (0.7.0-0ubuntu1~ubuntu18.04.1) ...\n",
            "Please, open the following URL in a web browser: https://accounts.google.com/o/oauth2/auth?client_id=32555940559.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&response_type=code&access_type=offline&approval_prompt=force\n",
            "··········\n",
            "Please, open the following URL in a web browser: https://accounts.google.com/o/oauth2/auth?client_id=32555940559.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&response_type=code&access_type=offline&approval_prompt=force\n",
            "Please enter the verification code: Access token retrieved correctly.\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "7yzpLX_atbFH",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "#训练一个基本模型，采用mnist 数据集，训练了一个模型\n",
        "## 关键点，实现了模型的保存到云网盘上\n",
        "\n",
        "1.     model_path = \"./test/model.ckpt\" 核 必须以‘./’ 开头，就会保存在云盘的根目录上。然后第二个test会创建一个目录把模型直接保存进去列表项\n",
        "2.  然后选择文件 ->保存 会自动保存在云网盘下test的目下，就可以在云网盘里面下载\n",
        "    "
      ]
    },
    {
      "metadata": {
        "id": "5UAx2aOFjBwc",
        "colab_type": "code",
        "outputId": "2edcc856-69b9-4d36-9caf-26c30c71d927",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 89
        }
      },
      "cell_type": "code",
      "source": [
        "from __future__ import print_function\n",
        "\n",
        "# Import MNIST data\n",
        "from tensorflow.examples.tutorials.mnist import input_data\n",
        "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n",
        "\n",
        "import tensorflow as tf\n",
        "\n",
        "# Parameters\n",
        "learning_rate = 0.001\n",
        "batch_size = 100\n",
        "display_step = 1\n",
        "model_path = \"./test/model.ckpt\"\n",
        "\n",
        "# Network Parameters\n",
        "n_hidden_1 = 256 # 1st layer number of features\n",
        "n_hidden_2 = 256 # 2nd layer number of features\n",
        "n_input = 784 # MNIST data input (img shape: 28*28)\n",
        "n_classes = 10 # MNIST total classes (0-9 digits)\n",
        "\n",
        "# tf Graph input\n",
        "x = tf.placeholder(\"float\", [None, n_input])\n",
        "y = tf.placeholder(\"float\", [None, n_classes])\n",
        "\n"
      ],
      "execution_count": 0,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Extracting MNIST_data/train-images-idx3-ubyte.gz\n",
            "Extracting MNIST_data/train-labels-idx1-ubyte.gz\n",
            "Extracting MNIST_data/t10k-images-idx3-ubyte.gz\n",
            "Extracting MNIST_data/t10k-labels-idx1-ubyte.gz\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "fCEYnXR2lDob",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "\n",
        "# Create model\n",
        "def multilayer_perceptron(x, weights, biases):\n",
        "    # Hidden layer with RELU activation\n",
        "    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])\n",
        "    layer_1 = tf.nn.relu(layer_1)\n",
        "    # Hidden layer with RELU activation\n",
        "    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])\n",
        "    layer_2 = tf.nn.relu(layer_2)\n",
        "    # Output layer with linear activation\n",
        "    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']\n",
        "    return out_layer\n",
        "\n",
        "# Store layers weight & bias\n",
        "weights = {\n",
        "    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),\n",
        "    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n",
        "    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))\n",
        "}\n",
        "biases = {\n",
        "    'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n",
        "    'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n",
        "    'out': tf.Variable(tf.random_normal([n_classes]))\n",
        "}\n",
        "\n",
        "# Construct model\n",
        "pred = multilayer_perceptron(x, weights, biases)\n",
        "\n",
        "# Define loss and optimizer\n",
        "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\n",
        "optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n",
        "\n",
        "# Initialize the variables (i.e. assign their default value)\n",
        "init = tf.global_variables_initializer()\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "mRDpKYZQlLgX",
        "colab_type": "code",
        "outputId": "c58fdcc3-a07d-4b53-ceb8-bb74c96be50c",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "cell_type": "code",
      "source": [
        "saver = tf.train.Saver()\n",
        "print(\"Starting 1st session...\")\n"
      ],
      "execution_count": 0,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Starting 1st session...\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "kuxvOHBglQ1w",
        "colab_type": "code",
        "outputId": "d5980ba7-90cf-4f5a-feed-23d3e7a5e240",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 449
        }
      },
      "cell_type": "code",
      "source": [
        "with tf.Session() as sess:\n",
        "\n",
        "    # Run the initializer\n",
        "    sess.run(init)\n",
        "\n",
        "    # Training cycle\n",
        "    for epoch in range(20):\n",
        "        avg_cost = 0.\n",
        "        total_batch = int(mnist.train.num_examples/batch_size)\n",
        "        # Loop over all batches\n",
        "        for i in range(total_batch):\n",
        "            batch_x, batch_y = mnist.train.next_batch(batch_size)\n",
        "            # Run optimization op (backprop) and cost op (to get loss value)\n",
        "            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,\n",
        "                                                          y: batch_y})\n",
        "            # Compute average loss\n",
        "            avg_cost += c / total_batch\n",
        "        # Display logs per epoch step\n",
        "        if epoch % display_step == 0:\n",
        "            print(\"Epoch:\", '%04d' % (epoch+1), \"cost=\", \\\n",
        "                \"{:.9f}\".format(avg_cost))\n",
        "    print(\"First Optimization Finished!\")\n",
        "\n",
        "    # Test model\n",
        "    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n",
        "    # Calculate accuracy\n",
        "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n",
        "    print(\"Accuracy:\", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))\n",
        "\n",
        "    # Save model weights to disk\n",
        "    save_path = saver.save(sess, model_path)\n",
        "    print(\"Model saved in file: %s\" % save_path)\n",
        "\n",
        "# Running a new session\n",
        "print(\"Starting 2nd session...\")"
      ],
      "execution_count": 0,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Epoch: 0001 cost= 157.880364637\n",
            "Epoch: 0002 cost= 40.935988136\n",
            "Epoch: 0003 cost= 25.919841922\n",
            "Epoch: 0004 cost= 18.143144945\n",
            "Epoch: 0005 cost= 13.329990612\n",
            "Epoch: 0006 cost= 10.058446161\n",
            "Epoch: 0007 cost= 7.478895636\n",
            "Epoch: 0008 cost= 5.516738385\n",
            "Epoch: 0009 cost= 4.323891135\n",
            "Epoch: 0010 cost= 3.208949505\n",
            "Epoch: 0011 cost= 2.384994497\n",
            "Epoch: 0012 cost= 1.850173553\n",
            "Epoch: 0013 cost= 1.507278592\n",
            "Epoch: 0014 cost= 1.133943096\n",
            "Epoch: 0015 cost= 0.861552837\n",
            "Epoch: 0016 cost= 0.798021430\n",
            "Epoch: 0017 cost= 0.648894878\n",
            "Epoch: 0018 cost= 0.545083262\n",
            "Epoch: 0019 cost= 0.469171598\n",
            "Epoch: 0020 cost= 0.498337911\n",
            "First Optimization Finished!\n",
            "Accuracy: 0.9492\n",
            "Model saved in file: ./test/model.ckpt\n",
            "Starting 2nd session...\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "W8l6ijdrx_Ey",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "使用以下方法一次可以下载一个文件下来，其他几个也可以采用类似的方法下载。\n",
        "我还是建议在云网盘里面使用客户端下载，毕竟网页下载很慢。"
      ]
    },
    {
      "metadata": {
        "id": "cIX7iLwEla2N",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "from google.colab import files\n",
        "files.download('./test/model.ckpt.index') \n",
        "\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "k4xcESS0l1KH",
        "colab_type": "code",
        "outputId": "0b7844ce-e360-45fa-d579-84323b6ebda4",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "cell_type": "code",
      "source": [
        "!ls -a"
      ],
      "execution_count": 0,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            ".  ..  adc.json  .config  MNIST_data  sample_data  test\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "X4UtC-8Rp1Df",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "指定当前云端的根目录"
      ]
    },
    {
      "metadata": {
        "id": "P_yg5QlPgqJq",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# 指定Google Drive云端硬盘的根目录，名为drive\n",
        "!mkdir -p drive\n",
        "!google-drive-ocamlfuse drive\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "ZbH8KUlKh60Z",
        "colab_type": "code",
        "outputId": "0a151736-272b-4d8c-c601-0806f9a646eb",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "cell_type": "code",
      "source": [
        "!ls -a"
      ],
      "execution_count": 0,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            ".  ..  adc.json  .config  drive  MNIST_data  sample_data  test\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "2bmC9HXBplLn",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "把所有云端的数据上传到当前路径下，然后就可以使用了"
      ]
    },
    {
      "metadata": {
        "id": "BzQdumfrjtiP",
        "colab_type": "code",
        "outputId": "57c88dd9-f751-44f4-90ca-542903261a5e",
        "colab": {
          "resources": {
            "http://localhost:8080/nbextensions/google.colab/files.js": {
              "data": "Ly8gQ29weXJpZ2h0IDIwMTcgR29vZ2xlIExMQwovLwovLyBMaWNlbnNlZCB1bmRlciB0aGUgQXBhY2hlIExpY2Vuc2UsIFZlcnNpb24gMi4wICh0aGUgIkxpY2Vuc2UiKTsKLy8geW91IG1heSBub3QgdXNlIHRoaXMgZmlsZSBleGNlcHQgaW4gY29tcGxpYW5jZSB3aXRoIHRoZSBMaWNlbnNlLgovLyBZb3UgbWF5IG9idGFpbiBhIGNvcHkgb2YgdGhlIExpY2Vuc2UgYXQKLy8KLy8gICAgICBodHRwO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Byb21pc2UsIHRpbWVvdXRQcm9taXNlLCBjYW5jZWxQcm9taXNlXSksCiAgICByZXNwb25zZTogewogICAgICBhY3Rpb246ICdzdGFydGluZycsCiAgICB9CiAgfTsKCiAgaWYgKCFmaWxlcykgewogICAgcmV0dXJuIHsKICAgICAgcmVzcG9uc2U6IHsKICAgICAgICBhY3Rpb246ICdjb21wbGV0ZScsCiAgICAgIH0KICAgIH07CiAgfQoKICBjYW5jZWwucmVtb3ZlKCk7CgogIC8vIERpc2FibGUgdGhlIGlucHV0IGVsZW1lbnQgc2luY2UgZnVydGhlciBwaWNrcyBhcmUgbm90IGFsbG93ZWQuCiAgaW5wdXRFbGVtZW50LmRpc2FibGVkID0gdHJ1ZTsKCiAgZm9yIChjb25zdCBmaWxlIG9mIGZpbGVzKSB7CiAgICBjb25zdCBsaSA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2xpJyk7CiAgICBsaS5hcHBlbmQoc3BhbihmaWxlLm5hbWUsIHtmb250V2VpZ2h0OiAnYm9sZCd9KSk7CiAgICBsaS5hcHBlbmQoc3BhbigKICAgICAgICBgKCR7ZmlsZS50eXBlIHx8ICduL2EnfSkgLSAke2ZpbGUuc2l6ZX0gYnl0ZXMsIGAgKwogICAgICAgIGBsYXN0IG1vZGlmaWVkOiAkewogICAgICAgICAgICBmaWxlLmxhc3RNb2RpZmllZERhdGUgPyBmaWxlLmxhc3RNb2RpZmllZERhdGUudG9Mb2NhbGVEYXRlU3RyaW5nKCkgOgogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAnbi9hJ30gLSBgKSk7CiAgICBjb25zdCBwZXJjZW50ID0gc3BhbignMCUgZG9uZScpOwogICAgbGkuYXBwZW5kQ2hpbGQocGVyY2VudCk7CgogICAgb3V0cHV0RWxlbWVudC5hcHBlbmRDaGlsZChsaSk7CgogICAgY29uc3QgZmlsZURhdGFQcm9taXNlID0gbmV3IFByb21pc2UoKHJlc29sdmUpID0+IHsKICAgICAgY29uc3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lbnQgPQogICAgICAgICAgYCR7TWF0aC5yb3VuZCgocG9zaXRpb24gLyBmaWxlRGF0YS5ieXRlTGVuZ3RoKSAqIDEwMCl9JSBkb25lYDsKICAgIH0KICB9CgogIC8vIEFsbCBkb25lLgogIHlpZWxkIHsKICAgIHJlc3BvbnNlOiB7CiAgICAgIGFjdGlvbjogJ2NvbXBsZXRlJywKICAgIH0KICB9Owp9CgpzY29wZS5nb29nbGUgPSBzY29wZS5nb29nbGUgfHwge307CnNjb3BlLmdvb2dsZS5jb2xhYiA9IHNjb3BlLmdvb2dsZS5jb2xhYiB8fCB7fTsKc2NvcGUuZ29vZ2xlLmNvbGFiLl9maWxlcyA9IHsKICBfdXBsb2FkRmlsZXMsCiAgX3VwbG9hZEZpbGVzQ29udGludWUsCn07Cn0pKHNlbGYpOwo=",
              "ok": true,
              "headers": [
                [
                  "content-type",
                  "application/javascript"
                ]
              ],
              "status": 200,
              "status_text": ""
            }
          },
          "base_uri": "https://localhost:8080/",
          "height": 75
        }
      },
      "cell_type": "code",
      "source": [
        "#Uploading the Dataset \n",
        "\n",
        "from google.colab import files\n",
        "\n",
        "uploaded = files.upload()"
      ],
      "execution_count": 0,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/html": [
              "\n",
              "     <input type=\"file\" id=\"files-46ad331b-5240-411b-a4f3-2d94f03388a8\" name=\"files[]\" multiple disabled />\n",
              "     <output id=\"result-46ad331b-5240-411b-a4f3-2d94f03388a8\">\n",
              "      Upload widget is only available when the cell has been executed in the\n",
              "      current browser session. Please rerun this cell to enable.\n",
              "      </output>\n",
              "      <script src=\"/nbextensions/google.colab/files.js\"></script> "
            ],
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ]
          },
          "metadata": {
            "tags": []
          }
        },
        {
          "output_type": "stream",
          "text": [
            "Saving 20180615063948513.jpg to 20180615063948513.jpg\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "Eqt0NPQjm5z_",
        "colab_type": "code",
        "outputId": "9ce7a0c8-87c3-40ad-afb5-c8cf46e05876",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "cell_type": "code",
      "source": [
        "from keras import applications\n",
        "from keras.preprocessing.image import load_img\n",
        "\n",
        "from keras.applications.vgg16 import decode_predictions\n",
        "\n",
        "# load an image from file\n",
        "image = load_img('drive/data/33.jpg', target_size=(224, 224))\n",
        "\n",
        "from keras.preprocessing.image import img_to_array\n",
        "\n",
        "# convert the image pixels to a numpy array\n",
        "image = img_to_array(image)\n",
        "\n",
        "# reshape data for the model\n",
        "image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))\n",
        "\n",
        "from keras.applications.vgg16 import preprocess_input\n",
        "\n",
        "# prepare the image for the VGG model\n",
        "image = preprocess_input(image)\n",
        "\n",
        "# predict the probability across all output classes\n",
        "# 在Keras中使用已经训练好的模型进行预测时，只要使用predict()函数即可。\n",
        "# VGG模型可以对图像在1000个类别中的分类情况进行预测。\n",
        "# 你可以想象利用softmax进行手写数字识别（MNIST）的情况，\n",
        "# 彼时输出是一个10维的向量，其中每个元素表示输入隶属于某个具体数字的概率。\n",
        "\n",
        "vgg16_model = applications.vgg16.VGG16()\n",
        "\n",
        "# from keras.applications.vgg16 import VGG16\n",
        "# model = VGG16()\n",
        "# print(vgg16_model.summary())\n",
        "\n",
        "\n",
        "\n",
        "# convert the probabilities to class labels\n",
        "\n",
        "\n",
        "yhat = vgg16_model.predict(image)\n",
        "\n",
        "label = decode_predictions(yhat)\n",
        "# retrieve the most likely result, e.g. highest probability\n",
        "label = label[0][0]\n",
        "# print the classification\n",
        "print('%s (%.2f%%)' % (label[1], label[2] * 100))\n"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Labrador_retriever (65.63%)\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "metadata": {
        "id": "D7Hgkgt0q7_P",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        ""
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "sAw3QhpdoYDG",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        ""
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}